import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { ImageReadTool } from 'projects/shared/src/public-api';
const IMAGE_ICON = `<svg t="1612923410230" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4783" width="200" height="200"><path d="M896 64 128 64C64 64 0 124.032 0 188.032L0 832c0 64 64 128 128 128l768 0c64 0 128-64 128-128L1024 188.032C1024 124.032 960 64 896 64zM296 227.968c70.72 0 128 57.28 128 128 0 70.72-57.28 128-128 128s-128-57.28-128-128C168 285.312 225.28 227.968 296 227.968zM971.008 615.744l-126.976-126.976L580.8 752l155.328 155.328-73.536 0-258.56-258.56-258.56 258.56c0 0-11.392 0.64-28.416-5.312-13.952-4.928-23.872-15.872-23.872-15.872l310.912-310.912L544 715.2l299.968-300.032 126.976 126.976L970.944 615.744z" p-id="4784"></path></svg>`;
@Component({
  selector: 'zlyt-image-loader',
  templateUrl: './image-loader.component.html',
  styleUrls: ['./image-loader.component.scss']
})
export class ImageLoaderComponent implements OnInit {

  @Output() imageChange = new EventEmitter<File>();
  public isEmpty = true;
  public image: File | null = null;
  public imageUrl = '';
  private preventDefaultHander = (event: Event) => event.preventDefault();

  constructor(matIconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
    matIconRegistry.addSvgIconLiteral('image-icon', sanitizer.bypassSecurityTrustHtml(IMAGE_ICON));
  }

  ngOnInit(): void {
  }

  async handlerFileDorp(event: DragEvent) {
    event.preventDefault();
    event.stopPropagation();
    const fileList = event.dataTransfer?.files;
    if (fileList?.length === 1) {
      const file = fileList[0];
      if (/^image\//.test(file.type)) {
        this.isEmpty = false;
        this.image = fileList[0];
        const name = this.image.name;
        const extension = name.split('.').pop() || '';
        this.imageChange.emit(this.image);
        this.imageUrl = await ImageReadTool.transBlobToUrl(this.image);
      }
    }
  }

  handleFileDragover(event: DragEvent) {
    event.preventDefault();
    event.stopPropagation();
  }

}
